package web;

import DAO.UserDAO;
import bean.Car;
import bean.Items;
import bean.Orders;
import bean.Users;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import service.Impl.UserServiceImpl;
import service.UserService;
import utils.BianHaoUtils;

import javax.jws.soap.SOAPBinding;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author 栋
 * @date 2022/11/14
 * @description
 */
@WebServlet("/userServlet")
public class UserServlet extends baseServlet {
    UserService userService = new UserServiceImpl();

    /**
     * 用户登录
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String phoneNumber = req.getParameter("phoneNumber");
        String pwd = req.getParameter("pwd");
        Users user = userService.login(phoneNumber, pwd);
        Car car=new Car();
        if (user == null) {
            //登录失败
            req.setAttribute("msg", "手机号或密码错误！");
            req.setAttribute("phoneNumber", phoneNumber);
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        } else {
            //登录成功
            req.getSession().setAttribute("user", user);
            req.getSession().setAttribute("car",car);
            req.getRequestDispatcher("/pages/user/after_log_main.jsp").forward(req, resp);
        }


    }

    /**
     * 用户注册
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("userName");
        String phoneNumber = req.getParameter("phoneNumber");
        String pwd = req.getParameter("pwd");
        String repwd = req.getParameter("repwd");
        String sex = req.getParameter("sex");
        String introduce = req.getParameter("introduce");
        String address = req.getParameter("address");
        if(phoneNumber.length()!=11|| !Pattern.compile("[0-9]*").matcher(phoneNumber).matches()){
            req.setAttribute("msg", "请输入正确的手机号！");
            req.setAttribute("userName", userName);
            req.getRequestDispatcher("/pages/user/register.jsp").forward(req, resp);
        }
        else if (!pwd.equals(repwd)) {
            //登录失败
            req.setAttribute("msg", "密码和确认密码不匹配！");
            req.setAttribute("phoneNumber", phoneNumber);
            req.setAttribute("userName", userName);
            req.getRequestDispatcher("/pages/user/register.jsp").forward(req, resp);
        } else {
            Users user = new Users(null, phoneNumber, userName, pwd, sex, introduce, null, null, address);
            boolean isSucc = userService.register(user);
            if (isSucc) {
                req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
            } else {
                req.setAttribute("msg", "该手机号已被注册！");
                req.setAttribute("userName", userName);
                req.getRequestDispatcher("/pages/user/register.jsp").forward(req, resp);
            }

        }
    }

    /**
     * 显示所有已上架商品
     *
     * @param req
     * @param resp
     * @throws ServletException
     */
    protected void showAllItems(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Items> items = userService.showItems();
        req.getSession().setAttribute("items", items);
        Users user =(Users) req.getSession().getAttribute("user");
        if(user==null){
            req.getRequestDispatcher("/pages/user/befor_log_main.jsp").forward(req, resp);
        }else{
            req.getRequestDispatcher("/pages/user/after_log_main.jsp").forward(req, resp);
        }

    }

    /**
     * 实名认证
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void realName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name=req.getParameter("name");
        String number=req.getParameter("number");
        String pwd=req.getParameter("pwd");
        String credit_number=req.getParameter("credit");
        String cre_pwd=req.getParameter("cre_pwd");
        Users user = (Users)req.getSession().getAttribute("user");
        if(userService.realName(user,name,number,pwd,credit_number,cre_pwd)){
            user.setStu_number(number);
            user.setCredit_number(credit_number);
            req.getSession().setAttribute("user", user);
            req.getRequestDispatcher("/pages/user/realNameSuc.jsp").forward(req, resp);
        }else{
            req.setAttribute("msg", "信息有误！");
            req.setAttribute("name",name);
            req.setAttribute("credit_number",credit_number);
            req.getRequestDispatcher("/pages/user/realname.jsp").forward(req, resp);
        }
    }

    /**
     * 是否实名认证
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void isRealName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Users user = (Users)req.getSession().getAttribute("user");
        String des = req.getParameter("des");
        if(user.getStu_number()==null){
            //未实名认证
            req.getRequestDispatcher("/pages/user/realname.jsp").forward(req, resp);
        } else{
            req.getRequestDispatcher("/pages/"+des).forward(req, resp);
        }
    }

    /**
     * 显示个人商品信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void showPersonalItems(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String user_id = req.getParameter("user_id");
        List<Items> personalItems = userService.showPersonalItems(user_id);
        if(personalItems.isEmpty()){
            req.setAttribute("msg", "您还未上架过商品！");
            req.getRequestDispatcher("/pages/items/personalItems.jsp").forward(req, resp);

        }else{
            req.getSession().setAttribute("personalItems",personalItems);
            req.getRequestDispatcher("/pages/items/personalItems.jsp").forward(req, resp);
        }
    }

    /**
     * 退出登录
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath());
    }

    /**
     * 显示个人信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void personalInfor(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/pages/user/showPersonalInfor.jsp").forward(req, resp);
    }

    protected void updateInfor(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Users user =(Users) req.getSession().getAttribute("user");
        String introduce = req.getParameter("introduce");
        String address = req.getParameter("address");
        user.setIntroduce(introduce);
        user.setAddress(address);
        if(userService.updateInfor(user)){
            //更新成功
            Users u = userService.login(user.getPhone_number(), user.getUser_pwd());
            req.setAttribute("msg","修改成功");
            req.getSession().setAttribute("user",u);
            req.getRequestDispatcher("/pages/user/updateInfor.jsp").forward(req, resp);
        }else{
            //更新失败
            Users u = userService.login(user.getPhone_number(), user.getUser_pwd());
            req.setAttribute("msg","银行卡号不存在");
            req.getSession().setAttribute("user",u);
            req.getRequestDispatcher("/pages/user/updateInfor.jsp").forward(req, resp);
        }
    }

    /**
     * 修改密码
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String lastpwd = req.getParameter("lastpwd");
        Users user = (Users)req.getSession().getAttribute("user");
        String pwd = req.getParameter("pwd");
        String repwd = req.getParameter("repwd");
        if(!pwd.equals(repwd)){
            req.setAttribute("msg","新密码和确认密码不一致");
            req.getRequestDispatcher("/pages/user/updatePwd.jsp").forward(req, resp);
        }else if(!lastpwd.equals(user.getUser_pwd())){
            req.setAttribute("msg","输入旧密码错误");
            req.getRequestDispatcher("/pages/user/updatePwd.jsp").forward(req, resp);
        }else{
            user.setUser_pwd(pwd);
            userService.updateInfor(user);
            req.setAttribute("msg","修改成功");
            req.getRequestDispatcher("/pages/user/updatePwd.jsp").forward(req, resp);
        }
    }

    protected void showItemsByType(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer type =Integer.valueOf(req.getParameter("type")) ;
        List<Items> items = userService.showItemsByType(type);
        req.getSession().setAttribute("items",items);
        Users user =(Users) req.getSession().getAttribute("user");
        if(items.size()==0){
            req.setAttribute("msg","空");
            if(user==null){
                req.getRequestDispatcher("/pages/user/befor_log_main.jsp").forward(req, resp);
            }else{
                req.getRequestDispatcher("/pages/user/after_log_main.jsp").forward(req, resp);
            }
        }else{

            if(user==null){
                req.getRequestDispatcher("/pages/user/befor_log_main.jsp").forward(req, resp);
            }else{
                req.getRequestDispatcher("/pages/user/after_log_main.jsp").forward(req, resp);
            }
        }
    }

    protected void searchItems(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        List<Items> items = userService.showItemsSearch("%" + name + "%");
        Users user =(Users) req.getSession().getAttribute("user");
        req.getSession().setAttribute("items",items);
        if(items.size()==0){
            req.setAttribute("msg","空");
            if(user==null){
                req.getRequestDispatcher("/pages/user/befor_log_main.jsp").forward(req, resp);
            }else{
                req.getRequestDispatcher("/pages/user/after_log_main.jsp").forward(req, resp);
            }
        }else{

            if(user==null){
                req.getRequestDispatcher("/pages/user/befor_log_main.jsp").forward(req, resp);
            }else{
                req.getRequestDispatcher("/pages/user/after_log_main.jsp").forward(req, resp);
            }
        }
    }

    protected void buyItems(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String item_id = req.getParameter("item_id");
        String itemInfor_name = req.getParameter("itemInfor_name");
        String price = req.getParameter("price");
        String count = req.getParameter("count");
        String itemInfor_method = req.getParameter("itemInfor_method");
        String itemInfor_address = req.getParameter("itemInfor_Address");
        String credit_pwd = req.getParameter("credit_pwd");
        Users user = (Users) req.getSession().getAttribute("user");
        if (userService.isInBlacklist(user.getUser_id())) {
            req.setAttribute("msg","你正在黑名单中，无法购买商品");
            req.getRequestDispatcher("/pages/items/itemInfor.jsp").forward(req, resp);
        }else {
            String credit_number = user.getCredit_number();
            Orders orders=new Orders(null,user.getUser_id(),item_id,itemInfor_method,itemInfor_name,Integer.valueOf(count), BigDecimal.valueOf(Double.valueOf(count)*Double.valueOf(price)), Date.valueOf(LocalDate.now()), Time.valueOf(LocalTime.now()),itemInfor_address,"否");
            String c = userService.buyItems(orders, credit_number, credit_pwd);
            req.setAttribute("msg",c);
            req.getRequestDispatcher("/pages/items/itemInfor.jsp").forward(req, resp);
        }

    }

    protected void addToCar(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String item_id = req.getParameter("item_id");
        String itemInfor_name = req.getParameter("itemInfor_name");
        String price = req.getParameter("price");
        String count = req.getParameter("count");
        String itemInfor_method = req.getParameter("itemInfor_method");
        String itemInfor_address = req.getParameter("itemInfor_Address");
        Users user = (Users) req.getSession().getAttribute("user");
        if(userService.isInBlacklist(user.getUser_id())){
            req.setAttribute("msg","你正在黑名单中，无法添加商品到购物车");
            req.getRequestDispatcher("/pages/items/itemInfor.jsp").forward(req, resp);
        }else{
            Orders orders=new Orders(null,user.getUser_id(),item_id,itemInfor_method,itemInfor_name,Integer.valueOf(count), BigDecimal.valueOf(Double.valueOf(count)*Double.valueOf(price)), null,null,itemInfor_address,"否");
            Car car = (Car)req.getSession().getAttribute("car");

            car.add(orders);
            req.getSession().setAttribute("car",car);
            req.setAttribute("msg","添加成功");
            req.getRequestDispatcher("/pages/items/itemInfor.jsp").forward(req, resp);
        }

    }
    protected void showCar(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Car car = (Car)req.getSession().getAttribute("car");
        if(car.getCnt()==0){
            req.setAttribute("msg","空");
            req.getRequestDispatcher("/pages/items/Car.jsp").forward(req, resp);
        }else{
            req.getRequestDispatcher("/pages/items/Car.jsp").forward(req, resp);
        }
    }

    protected void payAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String credit_pwd = req.getParameter("credit_pwd");
        Users user = (Users) req.getSession().getAttribute("user");
        Car car = (Car) req.getSession().getAttribute("car");
        Date date=Date.valueOf(LocalDate.now());
        Time time=Time.valueOf(LocalTime.now());
        String r = userService.payAll(user, car, credit_pwd, date, time);
        req.getSession().setAttribute("car",car);
        req.setAttribute("msg",r);
        req.getRequestDispatcher("/pages/items/Car.jsp").forward(req, resp);

    }
    protected void showOrders(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Users user = (Users) req.getSession().getAttribute("user");
        String option = req.getParameter("option");
        List<Orders> orders = userService.showOrders(user.getUser_id(),option);

        if(option.equals("0")){
            if(orders.isEmpty()){
                req.getSession().setAttribute("orders",null);
                req.setAttribute("msg","空");
                req.getRequestDispatcher("/pages/order/showOrders.jsp").forward(req, resp);
            }else{
                req.getSession().setAttribute("orders",orders);
                req.getRequestDispatcher("/pages/order/showOrders.jsp").forward(req, resp);
            }
        }else if(option.equals("-1")){
            if(orders.isEmpty()){
                req.getSession().setAttribute("orders",null);
                req.setAttribute("msg","空");
                req.getRequestDispatcher("/pages/order/showSendOrders.jsp").forward(req, resp);
            }else{
                req.getSession().setAttribute("orders",orders);
                req.getRequestDispatcher("/pages/order/showSendOrders.jsp").forward(req, resp);
            }
        }

    }
    protected void deleteFromCar(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Car car=(Car) req.getSession().getAttribute("car");
        String item_id = req.getParameter("item_id");
        for(int i=0;i<car.getCnt();i++){
            if(car.getLst().get(i).getItem_id().equals(item_id)){
                car.setTotalPrice(car.getTotalPrice().subtract(car.getLst().get(i).getTotal_price()));
                car.setCnt(car.getCnt()-1);
                car.getLst().remove(i);


                break;
            }
        }
        if(car.getCnt()==0){
            req.setAttribute("msg","空");
            req.getSession().setAttribute("car",car);
            req.getRequestDispatcher("/pages/items/Car.jsp").forward(req, resp);
        }else{
            req.getSession().setAttribute("car",car);
            req.getRequestDispatcher("/pages/items/Car.jsp").forward(req, resp);
        }


    }

    protected void confirmOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String order_id = req.getParameter("order_id");
        Users user =(Users) req.getSession().getAttribute("user");
        userService.confirmOrder(order_id);
        List<Orders> orders = userService.showOrders(user.getUser_id(),"0");
        req.getSession().setAttribute("orders",orders);
        req.getRequestDispatcher("/pages/order/showOrders.jsp").forward(req, resp);
    }

}